from .base import Task as TaskBase
from exec import run_cmd
from urllib.parse import quote, unquote
from common import check_args
from log import out


class Task(TaskBase):

    def out_encode(self, o):
        return quote('\n'.join(o).replace('<', '&lt;').replace('>', '&gt;'));

    def run(self):
        if check_args(self.task_params, 'cmd', 'echo'):
            raise Exception('执行命令任务参数错误: %s' % self.task_params)

        o, e = run_cmd(unquote(self.cmd))

        if self.echo == '0':
            return out("命令执行: %s\n\tstdout: %s\n\tstderr: %s" % (self.cmd, o, e))

        data = {}
        data['cmd'] = self.cmd
        data['stdout'] = self.out_encode(o) if o else 'no'
        data['stderr'] = self.out_encode(e) if e else 'no'

        return self.push(self.echo, 'echo', 'shell', **data)


